package com.sailing.xjpb.web.base.configuration;

import com.sailing.xjpb.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.util.ArrayList;
import java.util.List;

/**
 * 参数解析器自动装配-将自定义的参数解析器放在RequestBody解析器之前执行
 *
 * @author FanHaiChao
 * createDate 2023/3/22 15:34
 */
@Slf4j
public class BeforeRequestBodyHandlerMethodArgumentResolverConfigure implements InitializingBean {

    @Autowired
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;
    @Autowired
    private SailingWebMvcConfigurer sailingWebMvcConfigurer;

    /**
     * 使自定义的解析器在@requestBody的解析器之前执行
     */
    @Override
    public void afterPropertiesSet() {
        try {
            List<HandlerMethodArgumentResolver> argumentResolvers = requestMappingHandlerAdapter.getArgumentResolvers();
            List<HandlerMethodArgumentResolver> customArgumentResolvers = new ArrayList<>();
            assert argumentResolvers != null;
            for (HandlerMethodArgumentResolver argumentResolver : argumentResolvers) {
                if (argumentResolver instanceof RequestResponseBodyMethodProcessor) {
                    sailingWebMvcConfigurer.addArgumentResolvers(customArgumentResolvers);
                }
                customArgumentResolvers.add(argumentResolver);
            }
            requestMappingHandlerAdapter.setArgumentResolvers(customArgumentResolvers);
        } catch (Exception e) {
            throw BusinessException.businessError("设置自定义参数解析器出错!", e);
        }
    }

}